package com.smarthome.api.mobile;

import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 上传文件
 *
 * @author KongXiangyu
 * @since 1.0
 */
@Controller
@RequestMapping("/uploadFile")
public class UploadFile {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadFile.class);
    private static ResourceBundle ipcConfig = ResourceBundle.getBundle("conf/ipc-config.properties");
    @Resource
    private ServiceExporter mobileServiceExporter;

    @RequestMapping(value = "/image", produces = {"text/json"}, method = {RequestMethod.GET, RequestMethod.POST})
    public void image(@RequestParam("images") CommonsMultipartFile[] files, HttpServletRequest req, HttpServletResponse res) throws Exception {
        MobileResponse<List<String>> response = new MobileResponse<List<String>>();
        List<String> urls = new ArrayList<String>();
        /** add by dhc temp */
        res.setHeader("Access-Control-Allow-Origin", "*");
        if (ArrayUtils.isNotEmpty(files)) {
            for (CommonsMultipartFile file : files) {
                // 取文件格式后缀名
                String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));

                // 取当前时间戳作为文件名
                String filename = System.currentTimeMillis() + type;

                // 本地保存的绝对路径
                String baseDir = ipcConfig.getString("images.local.path");
                StringBuilder imageFullName = new StringBuilder();
                imageFullName.append(baseDir);

                // end of "/"
                if (baseDir.charAt(baseDir.length() - 1) != File.separatorChar) {
                    imageFullName.append(File.separatorChar);
                }

                imageFullName.append(filename);
                File imageFile = new File(imageFullName.toString());

                // check absolute path
                if (!imageFile.getParentFile().exists() && !imageFile.getParentFile().isDirectory()) {
                    imageFile.getParentFile().mkdirs();
                }

                imageFile.createNewFile();
                FileUtils.copyInputStreamToFile(file.getInputStream(), imageFile);

                // image 的外网访问地址
                urls.add(ipcConfig.getString("images.address") + "/" + filename);
            }
        } else {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        }
        response.setData(urls);
        String responseStr = mobileServiceExporter.parseJsonString(response, null);
        LOGGER.info("uploadFile-image-responseStr:" + responseStr);
        mobileServiceExporter.sendResponse(responseStr, res);
    }
}
